package com.hyk.commonLib.common.utils.netRequest;

import com.hyk.commonLib.common.utils.GsonUtils;
import com.hyk.commonLib.common.utils.SoftHashMap;
import com.hyk.commonLib.common.utils.netRequest.annotation.NetServerBaseUrl;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 贺玉琨 on 2019/7/6.
 */
public class DefaultNetUtilsImpl implements INetUtils {
    protected static final SoftHashMap<String, Retrofit> retrofitCacheMap = new SoftHashMap<>();

    public <T> T getServerInstance(Class<T> server) {
        String key = server.getName();
        Retrofit retrofit = retrofitCacheMap.get(key);
        if (retrofit == null) {
            NetServerBaseUrl baseUrl = server.getAnnotation(NetServerBaseUrl.class);
            if (baseUrl == null) {
                throw new RuntimeException("server应添加 NetServerBaseUrl 注解");
            }
            retrofit = getRetrofitBuilder(server, resolveUrl(baseUrl)).build();
            retrofitCacheMap.put(key, retrofit);
        }
        return retrofit.create(server);
    }

    protected <T> OkHttpClient.Builder getHttpClientBuilder(Class<T> server) {
        return new OkHttpClient.Builder()
                .callTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS);
    }

    protected <T> Retrofit.Builder getRetrofitBuilder(Class<T> server, String baseUrl) {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create(GsonUtils.getInstance()))
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) // 支持RxJava
                .client(getHttpClientBuilder(server).build());
    }

    protected String resolveUrl(NetServerBaseUrl baseUrl) {
        return baseUrl.value();
    }
}
